package lupita.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lupita.persistence.MySQLImpl;

/**
 * Servlet implementation class Top5ResponseSvt
 */
public class Top5ResponseSvt extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private MySQLImpl mysql;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Top5ResponseSvt() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		PrintWriter out = response.getWriter();
		try {
			mysql = new MySQLImpl();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		ResultSet result;
		StringBuffer json = new StringBuffer( "({ tags:[");
		
		try{
			mysql.openConnection();
			result=  mysql.selectSQL("select f.name as nombre,f.id as idfile, t.votos as vote from (top5 t join filetop5 ft on t.id=ft.idTop5) join file f on ft.idFile = f.id  order by votos DESC  limit 5 ");
		
			
			result.beforeFirst();
		
			System.out.println("TABLA top5");
		
			int vote;
			String file;
			int idfile;
						
			 
			
			
			while(result.next()) {
				vote = result.getInt("vote");
				file = result.getString("nombre");

				idfile = result.getInt("idfile");
				
			
				System.out.println(vote+" "+file+" ");
				String cadena= "{tag:'" + file + "',freq:'" + vote + "',indexfile:'" + idfile + "'}";
				
				json.append(cadena.toString());
				
				if(result.isLast()){
					json.append("]})");
				}
				else{
					json.append(",");
				}
				
			}
		
			mysql.closeConnection();
		
		}catch(Exception e){
			e.printStackTrace();
		}
		
		String resp = request.getParameter("callback") + json.toString();
		System.out.println(resp);
		out.print(resp);
	}

}
